
LS = {
    init: function() {
        document.title = LS.localized.appName;
        this.modalStack = [];
        this.modalBG = false;
        this.showingError = false;
        this.state = null;
        this.alertbox = new LS.notifier('#error_alert');
        
        // server time - local time
        this.localTimeDelta = 0;
        
        LS.user.checkState();
        return true;
    },
    /* URL configs */
    getURL: function(sub) {
        //return CAKE_ROOT+"index.php/" + sub +"?r="+Math.random();
        return CAKE_ROOT+"index.php/" + sub +"?r="+Math.random();
    },

    getAlternateURL: function(sub) {
        return CAKE_ROOT+"index_cake.php/" + sub +"?r="+Math.random();
    },
    
    /* UI General */
    lockForm: function(form, lock) {
        $(form+' input').attr('disabled', lock);
        if(!lock) {
            try {
                $(form+' input[type="password"]').val("");
                $(form+' input[type="password"]')[0].focus();
            } catch(e) {}
        }
    },
    showModal: function(o, fAct) {
        if(!this.modalBG) {
            this.modalBG = true;
            $('#modal_panel_bg').fadeTo(0, 0).show().fadeTo('normal', 0.6);
        }
        
        // Attach activate/deactivate functions,
        // this functions are called when return from or go to other views.
        var fActivate = function(){};
        if(fAct != null) fActivate = fAct;
        
        var obj = $(o);
        var that = this;
        obj.bind("activateView", function() {
            obj.fadeIn("def", fActivate);
        });
        obj.bind("deactivateView", function() {
            obj.fadeOut(300);
            that.alertbox.showError(null);
        });
        
        // Put in stack
        if(this.modalStack.length > 0)
            this.modalStack[this.modalStack.length-1].trigger("deactivateView");
        
        this.modalStack.push($(o).trigger("activateView"));
        
    },
    exitModal: function() {
        this.modalStack.pop().trigger("deactivateView");
        
        if(this.modalStack.length > 0)
            this.modalStack[this.modalStack.length-1].trigger("activateView");
        
        if(this.modalStack.length == 0) {
            $('#modal_panel_bg').fadeOut();
            this.modalBG = false;
        }
    },
    checkFormField: function(form, field, errmsg) {
        var o = $(form+' input[name="'+field+'"]');
        if(o.val() == "") {
            o.focus();
            
            var e = {};
            e[field] = errmsg;
            this.user.showRegError(e);
            
            throw errmsg;
        }
    },
    /* Utils */
    getFormData: function(form) {
        var formData = {};
        $(form+' input').each(function(){formData[this.name] = this.value;});
        return formData;
    },
    ajaxReturnedTimestamp: function(json_obj) {
        if(json_obj != null && json_obj["1"] != undefined) {
            this.updateLocalTimeDelta(json_obj["1"]);
        }
    },
    updateLocalTimeDelta: function(svrTime) {
        if(svrTime != null) {
            var delta = svrTime*1000.0 - (new Date().getTime());
            // tolerate 1000ms different
            if(delta < -1000.0 || delta > 1000.0) {
                this.localTimeDelta = delta;
            }
        }
    }
};


LS.Main = {
    init: function(user) {
        //document.title = "["+user.username+":"+user.realname+"] - CS Millionaire";
        document.title = user.username+"@"+LS.localized.appName;
        $('#welcome_msg').html("Hello "+user.realname+" ("+user.username+"),");
        
        $('#menu_top').fadeIn();
        $('#error_center').fadeIn();
        $('#main_outer').fadeIn();
        
        $('body').bind("ajaxError", function(e){
            LS.Main.onAjaxError(e);
        });
        
        LS.problem.init('#problems', '#description', '#buttons');
        LS.problem.reload();
        LS.scoreboard.init('#scoreboard');
        LS.scoreboard.reload();
        
        this.timerScoreboard = window.setInterval(function(){LS.scoreboard.reload();}, 2000);
        this.timerProblem = window.setInterval(function(){LS.problem.reload();},3000);
        this.timerTime = window.setInterval(function(){LS.Main.updateServerTime();}, 500);
    },
    updateServerTime: function() {
        var date = new Date().getTime() + LS.localTimeDelta;
        var truedate = new Date(date);
        var h = truedate.getHours(), m = truedate.getMinutes(), s = truedate.getSeconds();
        var tmp_str = ""+((h<10)?"0":"")+h+":"+((m<10)?"0":"")+m+":"+((s<10)?"0":"")+s;
        $('#svrtime').html("Time: <span class='svrtime'>"+tmp_str+"</span>");
        
        LS.problem.updateCountdownTimer();
    },
    showMsgAlert: function(msghtml) {
        $('#msgcontent').html(msghtml);
        LS.showModal('#msgbox_div', null);
    },
    onLogout: function() {
        try {
            LS.scoreboard.onLogout();
            LS.problem.onLogout();
        } catch(e) {
            document.location.reload();
        }
        //return;
        
        document.title = LS.localized.appName;
        $('#welcome_msg').html("");
        
        window.clearInterval(this.timerScoreboard);
        window.clearInterval(this.timerProblem);
        window.clearInterval(this.timerTime);
        this.timerScoreboard = null;
        this.timerProblem = null;
        this.timerTime = null;
    },
    onAjaxError: function(e) {
        //alert(e.statusText);
    }
};

LS.notifier = function(container) {
    this.container = container;
    
    this.msg_span = document.createElement("span");
    $(this.msg_span).addClass('alert_msg');
    $(this.container).append(this.msg_span);
    
    return this;
};

LS.notifier.prototype = {
    destroy: function() {
        $(this.msg_span).remove();
        delete this.msg_span;
        this.msg_span = null;
        delete this;
    },
    /* UI Notification bar */
    showNotification: function(text) {
        if(text == null) {
            $(this.container).hide();
            this.showingError = false;
        } else {
            $(this.msg_span).removeClass('error')
                            .removeClass('fatal')
                            .html(text);
            if(!this.showingError) {
                this.showingError = true;
                $(this.container).fadeIn();
            }
        }
    },
    showError: function(txt) {
        this.showNotification(txt);
        $(this.msg_span).addClass('error');
    },
    showFatal: function(txt) {
        this.modalBG = true;
        $('#modal_panel_bg').fadeTo(0, 0).show().fadeTo(500, 0.8);
        this.showNotification(txt);
        $(this.msg_span).addClass('fatal');
    }
};

LS.localized = {
    appName: "CSIE Millionaire",
    errorConnection: "無法和伺服器連接，請稍候再試。",
    errorConnectionFatal: "糟糕！發生了嚴重錯誤，請重新載入頁面。",
    registrationSuccess: "註冊成功！請重新登入。",
    temporaryError: "發生暫時性的錯誤，請稍待。",
    scoreboardErrorConnection: "記分板暫時無法更新",
    problemListErrorConnection: "問題列表暫時無法更新",
    registrationFormFieldErrors: {
        username: "此欄位不能為空",
        password: "此欄位不能為空",
        password_confirm: "此欄位不能為空",
        nickname: "此欄位不能為空",
        realname: "此欄位不能為空",
        student_id: "此欄位不能為空",
        email: "此欄位不能為空"
    },
    registrationPasswordConflict: "密碼不一致",
    problemWaitForAnswer: "請選擇答案",
    problemWaitForCommitment: "再按一次送出",
    problemNoAnswerSelected: "沒有選擇選項",
    problemNoProblemSelected: "沒選擇題目怎麼送出呢",
    commitingAnswer: "傳送中...",
    problemAnswerCommited: "答案已傳送",
    problemAnswerAlreadyCommited: "已答過此題",
    //answerCorrect: "答對囉！",
    //answerWrong: "答錯了",
    answerCorrect: "答案已傳送",
    answerWrong: "答案已傳送",
    problemCountdown: "剩餘時間：",
    problemClosed: "此題已結束"
};
function debug(message){
	$("#debug_output").html($("#debug_output").html()+"<div>"+message+"</div>");
}